﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MiniCap.Abstractions;
using MiniCap.Core;
using MiniCap.Storage;
using MiniCap.Transport;
using MiniCap.Workers;
using System;
using System.Threading.Tasks;

// See https://aka.ms/new-console-template for more information

namespace MiniCap.Sample;
public class Program
{
    static async Task Main(string[] args)
    {
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                // 1. MySQL Outbox Storage
                string mysqlConnStr = "Server=;User ID=root;Password=pwd;Database=testdb;";
                services.AddSingleton(_ => new MySqlOutboxStorage(mysqlConnStr,
                    _.GetRequiredService<Microsoft.Extensions.Logging.ILogger<MySqlOutboxStorage>>()));

                // 2. RabbitMQ Transport
                string rabbitHost = "";
                string rabbitUser = "";
                string rabbitPass = "";
                string rabbitVhost = "TestVhost";
                services.AddSingleton(_ => new RabbitMqTransport(rabbitHost, rabbitUser, rabbitPass, rabbitVhost));

                // 3. Publisher
                services.AddSingleton<IMiniCapPublisher, MiniCapPublisher>();
                services.AddHostedService<OutboxDispatcherService>();
            })
            .Build();
        await host.StartAsync();

        var publisher = host.Services.GetRequiredService<IMiniCapPublisher>();
        var transport = host.Services.GetRequiredService<RabbitMqTransport>();

        var storage = host.Services.GetRequiredService<MySqlOutboxStorage>();
        await storage.EnsureCreatedAsync(); // 创建表

        // 订阅逻辑 1
        transport.Subscribe("order.created", async message =>
        {
            Console.WriteLine($"[逻辑A] 处理订单消息: {message}");
            await Task.CompletedTask;
        });

        // 订阅逻辑 2
        transport.Subscribe("order.created", async message =>
        {
            Console.WriteLine($"[逻辑B] 写日志: {message}");
            await Task.CompletedTask;
        });

        // 发布消息
        await publisher.PublishAsync("order.created", new { OrderId = 1001, Amount = 500 });

        Console.WriteLine("消息已发送，按任意键退出...");
        Console.ReadKey();
    }
}